<template>
  <div>
    <ul>
      <transition-group appear name="animate__animated animate__bounce" enter-active-class="animate__fadeInRight"
        leave-active-class="animate__fadeOutRight">
        <li v-for="(item, index) in todoList" :key="item.id">
          <div>
            <input type="checkbox" v-model="item.compelte" />
            <span v-if="!item.redact">{{ item.title }}</span>
            <span v-else>
              <input type="text" v-model="item.title" class="iptRedact" @blur="redactBlur(item)" ref="blurChange" />
            </span>
          </div>
          <p>
            <button @click="handleRedact(item, $event)" class="redact">
              编辑
            </button>
            <button @click="handleDel(index)">删除</button>
          </p>
        </li>
      </transition-group>
    </ul>
  </div>
</template>

<script>
import 'animate.css';
export default {
  methods: {
    redactBlur (item) {
      item.redact = false
    },
    handleRedact (item) {
      if (Object.prototype.hasOwnProperty.call(item, 'redact')) {
        item.redact = true
      } else {
        this.$set(item, 'redact', true)
      }
      this.$nextTick(() => {
        this.$refs.blurChange[0].focus()
      })
    },
    handleDel (index) {
      this.todoList.splice(index, 1)
    },
    updateHandel () {
      // 每次更新计算总和是否和数组长度一样
      let num = this.todoList.reduce((pre, todo) => pre + todo.compelte, 0)
      this.$bus.$emit(
        'todoAll',
        num == this.todoList.length && num > 0,
        num,
        this.todoList.length
      )
    },
  },
  updated () {
    this.updateHandel()
  },
  data () {
    return {
      todoList: JSON.parse(localStorage.getItem('todos')) || [],
    }
  },
  watch: {
    todoList: {
      // 表示深度监视
      deep: true,
      // 然后是一个事件函数handler
      handler (value) {
        localStorage.setItem('todos', JSON.stringify(value))
      },
    },
  },
  mounted () {
    this.updateHandel()
    this.$bus.$on('todoAdd', (data) => {
      this.todoList.push(data)
    })
    this.$bus.$on('handleAll', (data) => {
      this.todoList.forEach((item) => {
        item.compelte = data
      })
    })
    this.$bus.$on('handleClear', () => {
      this.todoList = this.todoList.filter((item) => !item.compelte)
    })
  },
  beforeDestroy () {
    this.$bus.$off(['todoAdd', 'handleAll', 'handleClear'])
  },
}
</script>

<style lang="scss" scoped>
ul {
  width: 100%;
  li {
    display: flex;
    justify-content: space-between;
    border: 1px solid #ddd;
    margin: 5px 0;
    align-items: center;
    font-weight: 700;
    height: 30px;
    button {
      display: none;
      margin-right: 5px;
    }
    &:hover button {
      display: inline-block;
    }
    div {
      width: 80%;
    }
    .iptRedact {
      width: 50%;
      border: 2px solid #ddd;
      padding: 0 5px;
    }
    .redact {
      background: blue;
      box-shadow: 0 3px 2px 0px rgb(3, 3, 204);
    }
  }
}
</style>
